//
//  HMOAuthViewController.swift
//  Weibo
//
//  Created by 吴少飞 on 16/9/21.
//  Copyright © 2016年 wushaofei. All rights reserved.
//

import UIKit
import SVProgressHUD

let WeiboAppKey = "1477207980"
let WeiboRedirect_Uri = "http://www.itcast.cn"
let WeiboAppSecret = "92c8625cfcf319de93cc84c309334245"
class HMOAuthViewController: UIViewController {
    
    private lazy var webV = UIWebView()
    
    override func loadView() {
        
        webV.isOpaque = false
        
        webV.delegate = self
        view = webV
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        requestLoging()
        addNavItem()
    }
    
    //发送网络请求
    func requestLoging(){
        
        let url = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)")
        
        let  request = URLRequest(url: url!)
        
        webV.loadRequest(request)
        
    }
    
    //MARK -- 添加nav上的按钮
    func addNavItem() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(backAction))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动登录", target: self, action: #selector(autoLoginAction))
    }
    
    @objc private func backAction(){
        
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
        
    }
    
    @objc private func autoLoginAction() {
        
        
        webV.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = 'wsf521123@sina.com';document.getElementById('passwd').value = '6288qaz'")
        
    }
    


        
}

extension HMOAuthViewController:UIWebViewDelegate {
    
    
    
    //开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    //结束完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.url else {
            
            return false
        }
        
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
            
            return true
        }
        
        if let query = url.query,query.hasPrefix("code=") {
            
            let code = query.substring(from: "code=".endIndex)
            
            HMUserAccountViewModel.sharedUserAccountViewModel.requestAccessToken(code: code, callBack: { (isSuccess) in
                
                if isSuccess {
                    
                    
                    self.dismiss(animated: false, completion: { 
                        
                        print("登录成功")
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotification), object: self)
                    })
                }
                
            })
   
        }
        
        
        return false
    }

}















